/*********************************************************************************
 *      Copyright:  (C) 2017 luminqi
 *                  All rights reserved.
 *
 *       Filename:  linker.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(2017年08月23日)
 *         Author:  luminqi <958822582@qq.com>
 *      ChangeLog:  1, Release initial version on "2017年08月23日 00时21分52秒"
 *                 
 ********************************************************************************/

#include "linker.h"

/*创建有n个节点的链表*/
link_node *link_create(link_node *head, int n)
{
    link_node *tail_node = NULL;
    link_node *new_node = NULL;
    int i =0;
    
    head = (link_node *)malloc(sizeof(link_node));
    if(head==NULL)
    {
        return NULL;
    }

    tail_node = head;
    
    for (i=0;i<n;i++)
    {
        new_node = (link_node *)malloc(sizeof(link_node));
        if(new_node == NULL)
        {
            return NULL;
        }

        printf("input the data of node %d:",i+1);
        scanf("%d",&new_node->data);
        
        new_node->next = NULL;
        tail_node->next = new_node;
        tail_node = new_node;
    }
    return head;
}

/*遍历链表*/
void link_traverse(link_node *head)
{
    link_node *ptr = head->next;
    while(ptr)
    {
        printf("%d ",ptr->data);
        ptr = ptr ->next;
    }
    printf("\n");
    return;
}

/*在链表中第i个节点的位置插入新节点*/
int node_insert(link_node *head, int i, int data)
{
    link_node *ptr = head;
    int j = 0;
    link_node *new_node = NULL;

    while((ptr->next)&&(j<i-1))  //找到第i-1个节点的位置
    {
        ptr = ptr->next;  //直到ptr 指向第i-1个节点
        j++;
    }
    if(!(ptr->next)||(j>i-1))
    {
        return -1;
    }

    new_node = (link_node *)malloc(sizeof(link_node));
    if(new_node == NULL)
    {
        return -1;
    }
    new_node->data = data;
    new_node->next = ptr->next; //新节点指针域指向第i+1个节点
    ptr->next = new_node; //现在第i个节点就是新插入的节点
    return 0;
}

/*删除链表的第i 个节点*/
int node_delete(link_node *head, int i)
{
    link_node *ptr = head;
    link_node *tmp = NULL;
    int j =0;

    while((ptr->next)&&(j<i-1))
    {
        ptr = ptr->next;
        j++;
    }
    if(!(ptr->next)||(j>i-1))
    {
        return -1;
    }

    tmp = ptr->next;
    ptr->next = tmp->next;
    free(tmp);
    return 0;
}

/*链表的就地逆序*/
void link_reverse(link_node *head)
{
    link_node *last_ptr = NULL;
    link_node *cur_ptr = head->next;
    link_node *next_ptr = NULL;

    while(cur_ptr)
    {
        next_ptr = cur_ptr->next;
        cur_ptr->next = last_ptr;
        last_ptr = cur_ptr;
        cur_ptr = next_ptr;
    }
    head->next = last_ptr;
    return;
}

/*摧毁链表，即释放所有节点的内存*/
void link_destroy(link_node * head)
{
    link_node *ptr =NULL;
    while(head)
    {
        ptr = head;
        head = head->next;
        printf("free node:%d ",ptr->data);
        free(ptr);
    }
    return;
}




